package com.definity.toolkit.web.taglib;

import javax.servlet.jsp.JspException;

public abstract class ComponentFormTag extends BaseTag {

	private static final long serialVersionUID = -201560662241040283L;

	private String property;
	private String label;
	private String labelStyleClass;
	
	public ComponentFormTag() {
		setI18n("form");
	}
	
	public String getProperty() {
		return property;
	}

	public void setProperty(String property) {
		this.property = property;
	}
	
	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}
	
	public String getLabelStyleClass() {
		return labelStyleClass;
	}
	
	public void setLabelStyleClass(String labelStyleClass) {
		this.labelStyleClass = labelStyleClass;
	}
	
	@Override
	public final int doStartTag() throws JspException {
		FormTag formTag = (FormTag) findAncestorWithClass(this, FormTag.class);
		
		StringBuilder html = new StringBuilder();

		int result = doStartTag(formTag, html);
		write(html);
		
		return result;
	}

	@Override
	public final int doEndTag() throws JspException {
		FormTag formTag = (FormTag) findAncestorWithClass(this, FormTag.class);
		
		StringBuilder html = new StringBuilder();

		int result = doEndTag(formTag, html);
		write(html);
		
		return result;
	}

	protected int doStartTag(FormTag formTag, StringBuilder html) throws JspException {
		String domainReferenceName = formTag.getDomainReferenceName();
		Object value = formTag.getDomainInstanceValue(property);

		String id = domainReferenceName + "." + property;
		
		String label = this.label;
		if (label == null)
			label = id;
		
		html.append("\n" + createLabel(id, label, value, formTag));
		
		String startTag = createStartTag(getComponentName(), id, value);
		if (startTag != null)
			html.append("\n" + startTag);
		
		return SKIP_BODY;
	}
	
	protected int doEndTag(FormTag formTag, StringBuilder html) throws JspException {
		String domainReferenceName = formTag.getDomainReferenceName();
		Object value = formTag.getDomainInstanceValue(property);

		String id = domainReferenceName + "." + property;
		
		String endTag = createEndTag(getComponentName(), id, value);
		if (endTag != null)
			html.append(endTag);
		
		return EVAL_PAGE;
	}
	
	protected String createLabel(String id, String label, Object value, FormTag formTag) throws JspException {
		if (label == null || label.length() == 0)
			return "";
		return "<label for=\"" + id + "\" class=\"" + labelStyleClass + "\">" + i18n().tl(label) + "</label>";
	}

	protected abstract String getComponentName();
	
	protected abstract String createStartTag(String name, String id, Object value) throws JspException;

	protected abstract String createEndTag(String name, String id, Object value) throws JspException;
	
}
